<!-- purchaseDetailPage.vue -->
<template>
    <!-- 在页面顶部或底部添加加载遮罩 -->
    <div v-loading="submitting" class="purchase-contract-detail-container">
        <div class="purchase-contract-detail-container">
            <!-- Document Information Group -->
            <el-card class="info-card" shadow="never">
                <template #header>
                    <div class="card-header">
                        <div class="title-wrapper">
                            <span class="title-text">单据信息</span>
                            <span class="store-name">{{ purchaseContract.storeName }}</span>
                            <el-tag v-if="!this.editMode"
                                :type="purchaseContract.status.code === CommonOrderStatus.Passed.code ? 'success' : 'info'"
                                size="small" class="status-tag">
                                {{ purchaseContract.status.name }}
                            </el-tag>
                        </div>
                        <!-- Action Buttons -->
                        <div class="action-buttons" v-if="!this.editMode">
                            <el-button plain @click="handleCopy">
                                <el-icon>
                                    <CopyDocument />
                                </el-icon> 复制
                            </el-button>
                            <el-button plain @click="handlePrint" style="margin-right: 20px">
                                <el-icon>
                                    <Printer />
                                </el-icon> 打印
                            </el-button>
                            <el-button v-if="PurchaseContract.hasEditPermission()" type="primary" plain
                                @click="handleEdit">
                                <el-icon>
                                    <Edit />
                                </el-icon> 编辑
                            </el-button>
                            <el-button v-if="PurchaseContract.hasEditPermission()" type="danger" plain
                                @click="handleDelete">
                                <el-icon>
                                    <Delete />
                                </el-icon> 删除
                            </el-button>
                        </div>
                    </div>
                </template>
                <el-form ref="ruleFormRef" :model="formData" label-width="100px">
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <input-widget-web v-model="formData.title" label="单据标题" prop="title"
                                :readonly="!this.editMode" />
                        </el-col>
                        <el-col v-if="!this.editMode" :span="6">
                            <input-widget-web v-model="formData.docCode" label="单据编号" prop="docCode"
                                :readonly="!this.editMode" />
                        </el-col>

                        <el-col :span="6">
                            <partner-select v-model="formData.targetObject" label="供应商" prop="targetObject"
                                :readonly="!this.editMode" initialPartnerType="supplier"
                                :rules="[{ required: true, message: '请选择供应商', trigger: 'blur' }]"
                                :basicUiAction="basicUiAction" />
                        </el-col>

                        <el-col :span="6">
                            <warehouse-select v-model="formData.warehouse" label="仓库" prop="warehouse"
                                :readonly="!this.editMode" :inventoryUiAction="inventoryUiAction" />
                        </el-col>

                        <el-col :span="6">
                            <date-time-select v-model="formData.operateDate" label="采购日期" prop="operateDate"
                                :readonly="!this.editMode" type="datetime" />
                        </el-col>

                        <el-col :span="6">
                            <employee-select v-model="formData.operator" label="经办人" prop="operator"
                                :readonly="!this.editMode" :enterpriseMgtUiAction="enterpriseMgtUiAction" />
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>

            <!-- Purchase Items Group -->
            <el-card class="items-card" shadow="never">
                <template #header>
                    <div class="card-header">
                        <div class="title-wrapper">
                            <div class="summary-container">
                                <span class="title-text">采购商品</span>
                                <span class="total-info">
                                    共{{ purchaseContract.commmodityList.length }}件商品
                                </span>
                            </div>
                            <!-- 添加和删除按钮 -->
                            <div v-if="editMode" class="action-buttons">
                                <el-button type="primary" size="small" @click="handleAddCommodity">
                                    添加商品
                                </el-button>
                                <el-button type="danger" size="small" @click="handleDeleteSelectedCommodities">
                                    删除商品
                                </el-button>
                            </div>
                        </div>
                    </div>
                </template>

                <el-table :data="purchaseContract.commmodityList" style="width: 100%"
                    @selection-change="handleSelectionChange">
                    <!-- 勾选列 -->
                    <el-table-column type="selection" width="55" v-if="editMode" />
                    <el-table-column label="图片" width="150">
                        <template #default="scope">
                            <el-image v-if="scope.row.commodity.imgs" :src="scope.row.commodity.imgs.split(',')[0]"
                                fit="cover" class="commodity-image"></el-image>
                        </template>
                    </el-table-column>
                    <el-table-column label="商品名称" width="180">
                        <template #default="scope">
                            {{ scope.row.commodity.name }}
                        </template>
                    </el-table-column>
                    <el-table-column label="规格" width="180">
                        <template #default="scope">
                            {{ scope.row.commodity.standard }}
                        </template>
                    </el-table-column>
                    <el-table-column label="单位" width="80">
                        <template #default="scope">
                            {{ scope.row.commodity.unit?.name || '-' }}
                        </template>
                    </el-table-column>

                    <el-table-column label="数量" align="right" width="100">
                        <template #default="scope">
                            <input-cell :readonly="!editMode" :model-value="scope.row.count.value" :numberMode="true"
                                :precision="countPrecision"
                                @update:model-value="val => { scope.row.setCount(new CsDouble(val, countPrecision)); purchaseContract.calculatePriceAndQuantity(); }" />
                        </template>
                    </el-table-column>

                    <el-table-column label="单价" align="right" width="100">
                        <template #default="scope">
                            <input-cell :readonly="!editMode" :model-value="scope.row.singlePrice.value"
                                :numberMode="true" :precision="fundPrecision"
                                @update:model-value="val => { scope.row.setSinglePrice(new CsFundDouble(val)); purchaseContract.calculatePriceAndQuantity(); }" />
                        </template>
                    </el-table-column>

                    <el-table-column label="折扣%" align="right" width="100">
                        <template #default="scope">
                            <input-cell :readonly="!editMode" :model-value="scope.row.discount.value" :numberMode="true"
                                :precision="disCountRation"
                                @update:model-value="val => { scope.row.discount = new CsDouble(val, disCountRation); purchaseContract.calculatePriceAndQuantity(); }" />
                        </template>
                    </el-table-column>

                    <el-table-column label="折后总价" align="right" width="100">
                        <template #default="scope">

                            <input-cell :readonly="!editMode" :model-value="scope.row.batchPriceWithDiscount.value"
                                :numberMode="true" :precision="fundPrecision"
                                @update:model-value="val => { scope.row.setBatchPriceWithDiscount(new CsFundDouble(val, fundPrecision)); purchaseContract.calculatePriceAndQuantity(); }" />
                        </template>
                    </el-table-column>

                    <el-table-column label="税率(%)" align="right" width="100">
                        <template #default="scope">
                            <input-cell :readonly="!editMode" :model-value="scope.row.taxRate.value" :numberMode="true"
                                :precision="2"
                                @update:model-value="val => { scope.row.taxRate = new CsDouble(val, 2); purchaseContract.calculatePriceAndQuantity(); }" />
                        </template>
                    </el-table-column>

                    <el-table-column label="含税单价" align="right" width="100">
                        <template #default="scope">
                            <input-cell :readonly="!editMode" :model-value="scope.row.singlePriceAfterTax.value"
                                :numberMode="true" :precision="fundPrecision"
                                @update:model-value="val => { scope.row.setSinglePriceAfterTax(new CsFundDouble(val, fundPrecision)); purchaseContract.calculatePriceAndQuantity(); }" />
                        </template>
                    </el-table-column>

                    <el-table-column label="税额" align="right" width="100">
                        <template #default="scope">
                            <input-cell :readonly="true" :model-value="scope.row.tax.value" :numberMode="true"
                                :precision="fundPrecision" />
                        </template>
                    </el-table-column>

                    <el-table-column label="含税总价" align="right" width="100">
                        <template #default="scope">
                            <input-cell :readonly="!editMode" :model-value="scope.row.batchPriceWithTax.value"
                                :numberMode="true" :precision="fundPrecision"
                                @update:model-value="val => { scope.row.setBatchPriceWithTax(new CsFundDouble(val, fundPrecision)); purchaseContract.calculatePriceAndQuantity(); }" />
                        </template>
                    </el-table-column>

                    <el-table-column label="赠品" align="right" width="120">
                        <template #default="scope">
                            <span>{{ scope.row.isPromotional ? "是" : "否" }}</span>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>

            <el-row :gutter="16" class="summary-row">
                <el-col :span="12">
                    <el-card class="amount-summary-card" shadow="never">
                        <template #header>
                            <div class="card-header">
                                <div class="title-wrapper">
                                    <span class="title-text">金额汇总</span>
                                </div>
                            </div>
                        </template>

                        <div class="amount-summary-content">
                            <div class="amount-item">
                                <span class="label right-align">商品金额:</span>
                                <span class="value left-align">{{
                                    formatCurrency(purchaseContract.commodityPriceWithTax.value)
                                    }}</span>
                            </div>
                            <div class="amount-item">
                                <span class="label right-align">整单折扣率(%):</span>
                                <div class="value left-align">
                                    <input-cell :width="'200px'" :readonly="!editMode"
                                        :model-value="purchaseContract.discountRatio.value" :numberMode="true"
                                        :precision="disCountRation"
                                        @update:model-value="val => purchaseContract.discountRatio = new CsDouble(val, disCountRation)" />
                                </div>
                            </div>
                            <div class="amount-item">
                                <span class="label right-align">折后优惠:</span>
                                <div class="value left-align">
                                    <input-cell :width="'200px'" :readonly="!editMode"
                                        :model-value="purchaseContract.discount.value" :numberMode="true"
                                        :precision="fundPrecision"
                                        @update:model-value="val => purchaseContract.discount = new CsFundDouble(val, fundPrecision)" />
                                </div>
                            </div>

                            <div class="amount-item">
                                <span class="label right-align">其他费用:</span>
                                <div class="value left-align">
                                    <input-cell :width="'200px'" :readonly="!editMode"
                                        :model-value="purchaseContract.otherCost.value" :numberMode="true"
                                        :precision="fundPrecision"
                                        @update:model-value="val => purchaseContract.otherCost = new CsFundDouble(val, fundPrecision)" />
                                </div>
                            </div>

                            <div v-if="editMode" class="amount-item"
                                style="margin: 4px 0; padding-top: 0px; padding-bottom: 8px; border-bottom: 1px solid #ebeef5;">
                                <span class="label right-align"
                                    style="font-size: 16px; font-weight: bold; color: #606266 ;">合计:
                                </span>
                                <span class="value left-align"
                                    style="font-size: 16px; font-weight: bold; color: #E64D4D;">
                                    {{ formatCurrency(purchaseContract.totalMount.value) }}
                                </span>
                            </div>

                            <div v-if="editMode" class="amount-item">
                                <span class="label right-align"
                                    style="font-size: 16px; font-weight: bold; color: #606266 ;">付款信息
                                </span>
                            </div>

                            <div class="amount-item">
                                <span class="label right-align">预付冲抵:</span>
                                <value-checkbox-widget class="value left-align" :display-text="preOffsetText"
                                    :check-value="purchaseContract.enablePrePaymentOffset" :editable="editMode"
                                    width="200px"
                                    @update:check-value="val => purchaseContract.enablePrePaymentOffset = val">
                                    <span v-if="editMode">{{ "冲抵" + purchaseContract.prePaymentOffset.value }}</span>
                                </value-checkbox-widget>
                            </div>

                            <div class="amount-item">
                                <span class="label right-align">本次付款:</span>
                                <div class="value left-align">
                                    <input-cell :width="'200px'" :readonly="!editMode"
                                        :model-value="purchaseContract.payedMount.value" :numberMode="true"
                                        :precision="fundPrecision"
                                        @update:model-value="val => purchaseContract.payedMount = new CsFundDouble(val)" />
                                </div>
                            </div>

                            <div v-if="purchaseContract.payedMount.value != 0" class="amount-item">
                                <span class="label right-align">付款账户:</span>
                                <div class="value left-align" style="width: 200px;">
                                    <fund-account-select :readonly="!editMode" v-model="purchaseContract.fundAccount"
                                        prop="fundAccount" :fund-ui-action="fundUiAction" />
                                </div>
                            </div>

                            <div v-if="editMode" class="amount-item"
                                style="margin: 4px 0; padding-top: 0px; padding-bottom: 8px; ">
                                <span class="label right-align"
                                    style="font-size: 14px; font-weight: bold; color: #606266 ;">剩余应付:
                                </span>
                                <span class="value left-align"
                                    style="font-size: 14px; font-weight: bold; color: #E64D4D;">
                                    {{ formatCurrency(purchaseContract.remainAmount.value) }}
                                </span>
                            </div>

                            <div v-if="!editMode" class="amount-item">
                                <span class="label right-align">应付款:</span>
                                <span class="value left-align">{{ formatCurrency(purchaseContract.totalMount.value)
                                    }}</span>
                            </div>

                            <div v-if="!editMode" class="amount-item">
                                <span class="label right-align">实付款:</span>
                                <span class="value left-align">{{
                                    formatCurrency(purchaseContract.totalPayedMount(editMode).value)
                                    }}</span>
                            </div>
                        </div>
                    </el-card>
                </el-col>

                <el-col :span="12" class="other-info-col">
                    <!-- Other Information Group -->
                    <el-card class="other-info-card" shadow="never">
                        <template #header>
                            <div class="card-header">
                                <div class="title-wrapper">
                                    <span class="title-text">其他信息</span>
                                </div>
                            </div>
                        </template>

                        <el-descriptions v-if="!editMode" :column="1">
                            <el-descriptions-item v-if="latestUpdateInfo" label="最近更新">{{ latestUpdateInfo
                                }}</el-descriptions-item>
                            <el-descriptions-item label="制单人">{{ docMaker }}</el-descriptions-item>
                            <el-descriptions-item label="备注">
                                <div class="remark-content">{{ purchaseContract.remark || '-' }}</div>
                            </el-descriptions-item>
                        </el-descriptions>

                        <!-- 注意本处增加一个div , 不然第一个控件左对齐有问题，具体问题待查  -->
                        <div> </div>

                        <!-- 备注 -->
                        <input-widget-web class="value left-align" v-if="editMode" v-model="formData.remark" label="备注"
                            prop="remark" placeholder="请输入备注信息" :remarkMode="true" />
                    </el-card>
                </el-col>
            </el-row>

            <!-- 底部操作栏 (仅在编辑模式下显示) -->
            <bottom-bar :visible="editMode">
                <template #left>
                    <span class="doc-maker-info">制单人: {{ docMakerBottmBar }}</span>
                </template>
                <template #right>
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">提交</el-button>
                </template>
            </bottom-bar>

            <!-- 商品选择弹窗 -->
            <subcommodity-select-dialog ref="commoditySelectDialog" :basic-ui-action="basicUiAction"
                @select="handleCommoditySelect" />
        </div>
    </div>
</template>

<script>
import { PurchaseContract } from '../../public/engine/purchase/purchaseContract'
import { CommodityBatchWithTax } from '../../public/engine/sales/sales'
import { Employee } from '../../public/engine/enterpriseMgt/employee'
import { CsDouble } from '../../public/engine/common/csDouble'
import { CsFundDouble } from '../../public/engine/common/csFundDouble'
import { CommonOrderStatus } from '../../public/engine/common/docDefinition'
import { PurchaseUiAction } from '../../public/engine/uiAction/purchaseUiAction'
import { InventoryUiAction } from '../../public/engine/uiAction/inventoryUiAction'
import { Util } from '../../public/utils/util'
import { DateUtil } from '../../public/utils/dateUtil'
import { Engine } from '../../public/engine/engine'
import { ElMessage, ElMessageBox } from 'element-plus'
import { BasicUiAction } from '../../public/engine/uiAction/basicUiAction'
import { EnterpriseMgtUiAction } from '../../public/engine/uiAction/enterpriseMgtUiAction.js'
import { ActionResult, ActionResultType } from '../../public/engine/common/actionResult.js'
import InputWidgetWeb from '../../public/views/componentsWeb/InputWidgetWeb.vue'
import PartnerSelect from '../../public/views/componentsWeb/PartnerSelect.vue'
import WarehouseSelect from '../../public/views/componentsWeb/WarehouseSelect.vue'
import DateTimeSelect from '../../public/views/componentsWeb/DateTimeSelect.vue'
import EmployeeSelect from '../../public/views/componentsWeb/EmployeeSelect.vue'
import QualityInputCell from '../../public/views/componentsWeb/QualityInputCell.vue'
import ValueCheckboxWidget from '../../public/views/componentsWeb/ValueCheckboxWidget.vue'
import InputCell from '../../public/views/componentsWeb/InputCell.vue'
import SubcommoditySelectDialog from '../../views/inventory/subcommoditySelectDialog.vue'
import BottomBar from '../../public/views/componentsWeb/BottomBar.vue'
import EventBus from '../../public/engine/ipc/eventBus'
import TabUtil from '@/plugins/tab'
import { MessageUtil } from '@/utils/MessageUtil'
import { Definition } from '../../public/engine/common/definition.js'
import FundAccountSelect from '../../public/views/componentsWeb/FundAccountSelect.vue'
import { FundUiAction } from '../../public/engine/uiAction/fundUiAction'

export default {
    name: 'PurchaseContractDetailPage',
    components: {
        InputWidgetWeb,
        PartnerSelect,
        WarehouseSelect,
        DateTimeSelect,
        EmployeeSelect,
        QualityInputCell,
        InputCell,
        SubcommoditySelectDialog,
        BottomBar,
        ValueCheckboxWidget,
        FundAccountSelect
    },

    data() {
        return {
            purchaseContract: PurchaseContract.empty({
                operator: Engine.profile?.nickName,
                operatorId: Engine.profile?.id
            }),
            orgPurchaseContract: PurchaseContract.empty({
                operator: Engine.profile?.nickName,
                operatorId: Engine.profile?.id
            }),
            basicUiAction: new BasicUiAction(),
            purchaseUiAction: new PurchaseUiAction(),
            inventoryUiAction: new InventoryUiAction(),
            enterpriseMgtUiAction: new EnterpriseMgtUiAction(),
            loading: false,
            CommonOrderStatus,
            PurchaseContract,
            CsDouble,
            CsFundDouble,
            editMode: false,
            orderId: "",
            formData: {
                docCode: '',
                title: '',
                targetObject: null,
                warehouse: null,
                operateDate: null,
                operator: null,
                remark: '',
                updator: null,
                docMaker: null,
            },
            // 返回数据
            retValue: null,
            selectedCommodities: [],
            submitting: false, // 添加提交状态标识
            fundUiAction: new FundUiAction()
        }
    },

    mounted() {
        this.retValue = null;
        this.orderId = (this.$route.params.id || this.$route.query.id) || "";

        if (!Util.isEmpty(this.orderId)) {
            this.loadPurchaseContractData();
        } else {
            this.editMode = true;
            this.syncFormData();
        }
    },
    beforeUnmount() {
        if (this.retValue) {
            EventBus.emit('purchaseContractUpdated', null);
            this.retValue = null;
        }
    },

    deactivated() {
        if (this.retValue) {
            EventBus.emit('purchaseContractUpdated', null)
            this.retValue = null;
        }
    },

    computed: {
        latestUpdateInfo() {
            return (this.purchaseContract.updateor && this.purchaseContract.updateDate) ?
                (this.purchaseContract.updateor + "  " + DateUtil.getDayTitle(this.purchaseContract.updateDate)) : null;
        },

        docMaker() {
            return (this.purchaseContract.id && this.purchaseContract.docMaker && this.purchaseContract.recordDate) ?
                (this.purchaseContract.docMaker + "  " + DateUtil.getDayTitle(this.purchaseContract.recordDate)) : null
        },

        docMakerBottmBar() {
            return Engine.profile?.nickName.isEmpty
                ? Engine.profile?.userName
                : Engine.profile?.nickName;
        },

        fundPrecision() {
            return Definition.fundPrecision;
        },

        disCountRation() {
            return Definition.gConstDiscountRatePrecision;
        },

        preOffsetText() {
            return this.editMode ? "余额:" + Util.getFundString(this.purchaseContract.supplierPrePaymentAmount - this.purchaseContract.prePaymentOffset.value)
                : this.formatCurrency(this.purchaseContract.prePaymentOffset.value, true);
        }

    },

    methods: {
        syncFormData() {
            this.formData = {
                docCode: this.purchaseContract.docCode,
                title: this.purchaseContract.title,
                targetObject: this.purchaseContract.supplier,
                warehouse: this.purchaseContract.wareHouse,
                operateDate: this.purchaseContract.operateDate,
                operator: new Employee({ id: this.purchaseContract.operatorId, name: this.purchaseContract.operator }),
                remark: this.purchaseContract.remark,
                updator: (this.purchaseContract.updateor && this.purchaseContract.updateDate) ?
                    (this.purchaseContract.updateor + "  " + DateUtil.getDayTitle(this.purchaseContract.updateDate)) : null,
                docMaker: (this.purchaseContract.id && this.purchaseContract.docMaker && this.purchaseContract.recordDate) ?
                    (this.purchaseContract.docMaker + "  " + DateUtil.getDayTitle(this.purchaseContract.recordDate)) : null,
            };
        },

        fillWithFormData() {
            this.purchaseContract.title = this.formData.title;
            this.purchaseContract.supplier = this.formData.targetObject;
            this.purchaseContract.wareHouse = this.formData.warehouse;

            // formData.operateDate 控件变更日期会转换为字符串，这里需要转换回Date对象
            if (!(this.formData.operateDate instanceof Date)) {
                this.purchaseContract.operateDate = DateUtil.strToDate(this.formData.operateDate);
            } else {
                this.purchaseContract.operateDate = this.formData.operateDate;
            }

            this.purchaseContract.setOperator({
                operator: this.formData.operator.name,
                operatorId: this.formData.operator.id
            });
            this.purchaseContract.remark = this.formData.remark;
        },

        // 商品选择 items 类型 SubCommodityInventorySumData
        handleCommoditySelect(items) {
            if (items && items.length > 0) {
                for (let commodity of items) {
                    // 检查商品是否已存在
                    const exists = this.purchaseContract.commmodityList.some(
                        item => item.commodity.id === commodity.subCommodity.id
                    );

                    if (!exists) {
                        let batch = new CommodityBatchWithTax({
                            commodity: commodity.subCommodity,
                            count: new CsDouble(1),
                            availableCount: commodity.availableCount,
                            inventoryCount: commodity.totalInventoryCount,
                            batchPrice: commodity.subCommodity.purchasePrice,
                            singlePrice: commodity.subCommodity.purchasePrice
                        });
                        this.purchaseContract.addCommodityBatch(batch);
                    } else {
                        ElMessage.warning(`商品[${commodity.subCommodity.name}]已存在`);
                    }
                }
            }
        },

        handleCopy() {
            this.purchaseContract = PurchaseContract.clone(this.purchaseContract);
            this.purchaseContract.id = '';
            this.purchaseContract.orderBeforeEdit = null;
            this.editMode = true;
            MessageUtil.showSuccessMsg("复制完成");
        },

        handlePrint() { },

        handleEdit() {
            this.editMode = true;
        },

        async handleDelete() {
            if (Util.isEmpty(this.purchaseContract.id)) {
                TabUtil.closePage();
            } else {
                try {
                    await ElMessageBox.confirm("确定要删除该采购单据吗？", "删除确认", {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    });

                    this.submitting = true;

                    let delResult = await this.purchaseUiAction.removePurchaseOrder({
                        orderId: this.purchaseContract.id,
                        docType: this.purchaseContract.docType
                    });

                    if (delResult == null) {
                        this.retValue = new ActionResult({ type: ActionResultType.Del });
                        MessageUtil.showSuccessMsg("删除成功");
                        TabUtil.closePage();
                    }
                } catch (error) {
                    if (error !== 'cancel') {
                        console.error("purchaseContractDetailPage handleDelete error:", error);
                        ElMessage.error("删除操作失败");
                    }
                } finally {
                    this.submitting = false;
                }
            }
        },

        handleAddCommodity() {
            if (this.formData.warehouse == null ||
                this.formData.warehouse.id == null ||
                Util.isEmpty(this.formData.warehouse.id)) {
                MessageUtil.showWarningMsg("请先选择仓库");
                return;
            }

            this.$refs.commoditySelectDialog.open(
                this.purchaseContract.commmodityList.map(item => ({
                    subCommodity: item.commodity
                })),
                {
                    warehouse: this.formData.warehouse
                }
            );
        },

        handleSelectionChange(selection) {
            this.selectedCommodities = selection;
        },

        handleDeleteSelectedCommodities() {
            if (this.selectedCommodities.length === 0) {
                ElMessage.warning('请至少选择一个商品进行删除');
                return;
            }

            // 删除选中的商品
            this.selectedCommodities.forEach(commodity => {
                this.purchaseContract.removeCommodityBatch(commodity);
            });

            // 清空选中
            this.selectedCommodities = [];
        },

        // 取消编辑
        handleCancel() {
            this.purchaseContract = PurchaseContract.clone(this.orgPurchaseContract);
            this.editMode = false;
        },

        async handleSubmit() {

            try {
                // First validate the form
                await this.$refs.ruleFormRef.validate();
                // 验证表单
                const validationError = this.purchaseContract.validateOrder();
                if (validationError) {

                    if (validationError.errorMsg) {

                        if (validationError.msgBoxConfirm) {
                            try {
                                await ElMessageBox.confirm(
                                    validationError.errorMsg,
                                    '信息错误',
                                    {
                                        confirmButtonText: '确认',
                                        type: 'error'
                                    }
                                );

                                // 错误信息直接返回
                                return;

                            } catch (confirmError) {
                                // User cancelled
                                this.submitting = false;
                                return;
                            }
                        }
                        else {

                            ElMessage.error(validationError.errorMsg);
                            return;
                        }
                    }
                    else if (validationError.warningMsg) {
                        if (validationError.msgBoxConfirm) {
                            try {
                                await ElMessageBox.confirm(
                                    validationError.warningMsg,
                                    '确认提交',
                                    {
                                        confirmButtonText: '确认',
                                        cancelButtonText: '取消',
                                        type: 'warning'
                                    }
                                );

                            } catch (confirmError) {
                                // User cancelled
                                this.submitting = false;
                                return;
                            }
                        }
                        else {

                            ElMessage.error("validationError.errorMsg");
                            return;
                        }
                    }


                }

                this.submitting = true;
                this.fillWithFormData();
               // console.log('提交采购单数据', this.purchaseContract.toJson());

               // ElMessage.error("校验测试，暂不提交!");
               // return;

                const orderResult = await this.purchaseUiAction.updateOrCreatePurchaseContract(this.purchaseContract, true);

                if (orderResult) {
                    if (Util.isEmpty(this.purchaseContract.id)) {
                        this.retValue = new ActionResult({ type: ActionResultType.New });
                    } else {
                        this.retValue = new ActionResult({ type: ActionResultType.UpdateCommon });
                    }
                }

                if (orderResult) {
                    // 刷新订单页面
                    ElMessage.success("提交保存成功");
                    this.orderId = orderResult.id;
                    this.editMode = false;
                    this.loadPurchaseContractData();
                }
            } catch (error) {
                console.error('保存失败', error);
                ElMessage.error("保存失败");
            } finally {
                this.submitting = false;
            }
        },

        async loadPurchaseContractData() {
            try {
                this.loading = true;
                const res = await this.purchaseUiAction.getPurchaseDetailInfo(this.orderId);

                if (res) {
                    this.purchaseContract = res;
                    this.orgPurchaseContract = PurchaseContract.clone(res);
                    this.syncFormData();
                } else {
                    ElMessage.error('获取采购单详情失败');
                }
            } catch (error) {
                console.error('加载采购单数据失败:', error);
                ElMessage.error('加载采购单数据失败');
            } finally {
                this.loading = false;
            }
        },

        formatCount(value, withSignal = false) {
            return Util.getCountString(value, null, { withPrePositiveNegtiveSignal: withSignal });
        },

        formatCurrency(value, readOnlyZeroDashLine = false) {

            return Util.getFundString(value, { zeroDashLine: readOnlyZeroDashLine && !this.editMode });
        }
    }
}
</script>

<style scoped>
.summary-row {
    margin-bottom: 16px;
    display: flex;
    align-items: stretch;
}

.summary-row .el-col {
    display: flex;
    flex-direction: column;
}

.summary-row .el-card {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.summary-row .el-card .el-card__body {
    flex: 1;
    display: flex;
    flex-direction: column;
}

/* For the other info card specifically, we need to make its content stretch */
.other-info-card .el-card__body>*:first-child {
    flex: 1;
    display: flex;
    flex-direction: column;
}

/* Add these styles to the existing ones */
.amount-summary-content {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.amount-item {
    display: flex;
    align-items: center;
}

.amount-item .label.right-align {
    text-align: right;
    flex: 0 0 100px;
    /* Fixed width for labels */
    color: #606266;
    margin-right: 12px;
    font-size: 13px;
}

.amount-item .value.left-align {
    text-align: left;
    flex: 1;
    /* Take remaining space 
  font-weight: bold;
  */
    font-size: 13px;
}

.amount-item .total-amount .value.left-align {
    color: #E64D4D;
    font-size: 16px;
}

.purchase-contract-detail-container {
    padding: 16px;
    padding-bottom: 80px;
    /* 留出bottom bar的空间 */
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.action-buttons {
    display: flex;
    gap: 12px;
    margin-bottom: 0px;
    padding: 0 16px;
}

.title-wrapper {
    display: flex;
    align-items: center;
    gap: 12px;
}

.summary-container {
    flex: 1;
    min-width: 300px;
    display: flex;
    align-items: center;
    gap: 12px;
}

.total-info {
    color: #606266;
    font-size: 14px;
    white-space: nowrap;
}

.store-name {
    font-size: 12px;
    color: #606266;
}

.title-text {
    font-size: 16px;
    font-weight: bold;
}

.status-tag {
    margin-left: 12px;
}

.commodity-image {
    width: 40px;
    height: 40px;
    margin-right: 12px;
}

.remark-content {
    white-space: pre-wrap;
    word-break: break-all;
}

.info-card,
.items-card,
.amount-summary-card,
.other-info-card {
    margin-bottom: 16px;
    border-radius: 8px;
}

.amount-item {
    display: flex;
    justify-content: space-between;
    padding: 0px 0;
}

.amount-item .label {
    color: #606266;
}

.amount-item .value {
    font-weight: bold;
}

.total-amount .value {
    color: #E64D4D;
    font-size: 16px;
}
</style>